const LogModel = require('../../model/Log');
const moment = require('moment')
const request = require('request')
const ObjectID = require('mongodb').ObjectID;
const ExpenseHistory = require('../../model/ExpenseHistory')
const User = require('../../model/User')
const PointHistory = require('../../model/PointHistory')
const Store = require('../../model/Store')
const Member = require('../../model/Member')
const UserPoint = require('../../model/userPoint')
const MemberCard = require('../../model/MemberCard')
const Role = require('../../model/Role')
const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken')

module.exports = {

    //获取日志列表
    getExpenseHistoryList: async (req, res, next) => {
        try {
            if (req.body.startDate) {
                var startDate = new Date(req.body.startDate)
            }
            if (req.body.endDate) {
                var endDate = new Date(req.body.endDate)
            }
            let option = {}
            option.isDelete = 0
            if(req.body.billNumber){
                option.billNumber = new RegExp(req.body.billNumber)
            }
            if (req.body.verify) {
                option.verify = req.body.verify
            }
            if (req.body.userId) {
                let user = await User.findOne({ _id: req.body.userId, isDelete: 0 }).exec()
                option.openid = user.openid
            }
            if (req.body.id) {
                option.store = ObjectID(req.body.id)
            } else if (req.session.user.store.length !== 0) {
                let storeId = []
                req.session.user.store.forEach(e => {
                    storeId.push({ store: ObjectID(e) })
                })
                option.$or = storeId
            }
            if (req.body.memberNo) {
                let member = (await Member.find({ code: new RegExp(req.body.memberNo), isDelete: 0 }, '_id').exec()).map(e=>{return e._id})
                option.member = {$in:member}
            }
            if (req.body.cellphone) {
                option.cellphone = new RegExp(req.body.cellphone)
            }
            if (startDate && !endDate) {
                option.createdAt = { $gte: startDate }
            } else if (!startDate && endDate) {
                option.createdAt = { $lte: endDate }
            } else if (startDate && endDate) {
                option.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            }
            let allExpenseHistory = await ExpenseHistory.aggregate([
                {
                    $match: option
                }
            ]).exec()
            // let count = await ExpenseHistory.countDocuments(option).exec()
            let count = allExpenseHistory.length
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            // .find(option).skip((page - 1) * pageSize).limit(pageSize).populate('order store member').sort({ createdAt: -1 })
            let expenseHistory = await ExpenseHistory.aggregate([
                {
                    $match: option
                },
                {
                    $sort: {
                        createdAt: -1
                    }
                },
                {
                    $skip: ((page - 1) * pageSize)
                },
                {
                    $limit: pageSize
                },
                {
                    $lookup: {
                        from: "userPoint",
                        localField: 'openid',
                        foreignField: 'openid',
                        as: 'userPoint'
                    }
                },
                {
                    $lookup: {
                        from: "store",
                        localField: 'store',
                        foreignField: '_id',
                        as: 'store'
                    },
                },
                {
                    $lookup: {
                        from: "member",
                        localField: 'member',
                        foreignField: '_id',
                        as: 'member'
                    }
                },
                {
                    $lookup: {
                        from: "order",
                        localField: 'order',
                        foreignField: '_id',
                        as: 'order'
                    }
                },
                {
                    $lookup: {
                        from: "staff",
                        localField: 'staff',
                        foreignField: '_id',
                        as: 'staff'
                    }
                },
                {
                    $lookup: {
                        from: "adminUser",
                        localField: 'account',
                        foreignField: '_id',
                        as: 'account'
                    }
                }
            ]).exec()
            let giftPoint = 0
            let storeGiftPoint = 0
            let storePendingPoint = 0
            let usedPoint = 0
            let expiredPoint = 0
            let totalPoint = 0
            let currentPoint = 0
            let unreviewed = 0
            let unverify = 0
            let expiredPointUser = []
            let totalPointUser = []
            let currentPointUser = []
            await allExpenseHistory.forEach(e=>{
                giftPoint = giftPoint + e.earnPoints
                storeGiftPoint = storeGiftPoint + (e.verify === 1 ? e.earnPoints : 0)
                storePendingPoint = storePendingPoint + (e.verify === 0 ? e.earnPoints : 0)
                usedPoint = usedPoint + e.point
                unverify = unverify + (e.verify === 0 ? 1:0)
                unreviewed = unreviewed + (e.review === 0 ? 1:0)
            })
            await expenseHistory.forEach(e => {
                e.member = e.member[0]
                e.store = e.store[0]
                e.userPoint = e.userPoint[0]
                // giftPoint = giftPoint + e.earnPoints
                // storeGiftPoint = storeGiftPoint + e.verify === 1 ? e.earnPoints : 0
                // storePendingPoint = storePendingPoint + e.verify === 0 ? e.earnPoints : 0
                // usedPoint = usedPoint + e.point
                let index = expiredPointUser.indexOf(String(e.userPoint._id))
                if (e.userPoint.expiredPoint && (index === -1)) {
                    expiredPoint = expiredPoint + e.userPoint.expiredPoint
                    expiredPointUser.push(String(e.userPoint._id))
                }
                let totalPointUserIndex = totalPointUser.indexOf(String(e.userPoint._id))
                if (e.userPoint.total && (totalPointUserIndex === -1)) {
                    totalPoint = totalPoint + e.userPoint.total
                    totalPointUser.push(String(e.userPoint._id))
                }
                let currentPointUserIndex = currentPointUser.indexOf(String(e.userPoint._id))
                if (e.userPoint.expiredPoint && (currentPointUserIndex === -1)) {
                    currentPoint = currentPoint + e.userPoint.current
                    currentPointUser.push(String(e.userPoint._id))
                }
            });
            let result = {}
            result.giftPoint = giftPoint
            result.usedPoint = usedPoint
            result.total = count
            result.currentPage = page
            result.data = expenseHistory
            result.pageSize = pageSize
            result.expiredPoint = expiredPoint
            result.totalPoint = totalPoint
            result.currentPoint = currentPoint
            result.storeGiftPoint = storeGiftPoint
            result.storePendingPoint = storePendingPoint
            result.unverify = unverify
            result.unreviewed = unreviewed
            return res.ok('获取消费记录成功', result)

        } catch (e) {
            next(e)
        }
    },


    getOneExpenseHistory: async (req, res, next) => {
        try {
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).populate('order store member').exec()
            res.ok('获取成功', expenseHistory)
        } catch (e) {
            next(e)
        }
    },


    changeUserExpenseHistory: async (req, res, next) => {
        try {
            return res.ok('未完成', req.body)

            let user = await User.findOne({ cellphone: req.body.cellphone, isDelete: 0 }).exec()
            if (user == null) {
                return res.ok('未找到用户')
            }
            let rate = user.vip == 1 ? 15 : 10
            if (req.body.id) {
                let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
                expenseHistory.openid = user.openid,
                    expenseHistory.unionID = user.unionID,
                    expenseHistory.cellphone = req.body.cellphone,
                    expenseHistory.store = req.body.store,
                    expenseHistory.order = req.body.order,
                    expenseHistory.updatedAt = new Date(),
                    expenseHistory.amount = req.body.amount, // 价格
                    expenseHistory.memo = req.body.memo, //人工操作备注
                    expenseHistory.rate = rate, //10为10%
                    await expenseHistory.save()
                res.ok('消费记录修改成功', newExpenseHistory)
            } else {
                let rate = user.vip == 0 ? 10 : 15
                let newExpenseHistory = new ExpenseHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    cellphone: req.body.cellphone,
                    store: req.body.store,
                    order: req.body.order,
                    updatedAt: new Date(),
                    isDelete: 0,
                    amount: req.body.amount, // 价格
                    memo: req.body.memo, //人工操作备注
                    rate: rate, //10为10%
                })
                await newExpenseHistory.save()
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    order: req.body.order,
                    expenseHistory: newExpenseHistory._id,
                    expenseDate: new Date(),
                    memo: req.body.memo, //人工操作备注
                    manual: 1, // 1位人工，0为自动
                    amount: req.body.amount * rate / 100, // 变动的积分数量
                    type: req.body.amount > 0 ? 0 : 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                res.ok('消费记录创建成功', newExpenseHistory)
            }

            // let member = await Member.findOne({ openid: user.openid }, 'point').exec()
        } catch (e) {
            next(e)
        }
    },


    addUserExpenseHistory: async (req, res, next) => {
        try {
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let user = await User.findOne({ _id: req.body.user, isDelete: 0 }).exec()
            let store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let payPrice = Number(req.body.amount)
            let point = Number(req.body.point)
            if(!req.body.amount){
                return res.send({code:201,msg:"消费金额未填写"})
            }
            if (req.body.usePoint == 1) {
                // console.log(req.body.point,userPoint.current)
                if (point > userPoint.current) {
                    return res.send({ code: 201, msg: '积分不足' })
                }
                // console.log(payPrice,point,payPrice<point)
                if (payPrice < point) {
                    return res.send({ code: 201, msg: '使用积分大于消费金额' })
                }
                payPrice = payPrice - point
            }
            let changePoint = Math.round(payPrice * store.attribute / 100)
            let attribute = store.attribute
            if (user.vip == 1) {
                changePoint = Math.round(payPrice * store.attributeVIP / 100)
                attribute = store.attributeVIP
            }
            if(req.body.notGivePoint == 1){
                changePoint = 0
            }
            let newExpenseHistory = new ExpenseHistory({
                openid: user.openid,
                unionID: user.unionID,
                cellphone: user.cellphone,
                store: req.body.store,
                member: member._id,
                updatedAt: new Date(),
                isDelete: 0,
                usePoint: req.body.usePoint, //0不使用，1使用
                amount: req.body.amount, // 价格（未抵扣积分）
                payPrice: payPrice, //支付价格（抵扣积分后）
                point: point,
                earnPoints: changePoint,
                pendingPoint:changePoint,
                memo: req.body.memo, //人工操作备注
                rate: attribute, //10为10%
                account: req.session.user._id,
                verify: 0,
                review:0,
                billNumber:req.body.billNumber,
                billImage:req.body.billImage
            })
            await newExpenseHistory.save()
            if (changePoint > 0) {
                if(userPoint.pendingPoint==undefined){
                    userPoint.pendingPoint =changePoint
                }else{
                    userPoint.pendingPoint = userPoint.pendingPoint + changePoint
                }
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            if (req.body.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: newExpenseHistory._id,
                    expenseDate: newExpenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: point, // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point - point
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current - point
                userPoint.updatedAt = new Date()
                await userPoint.save()
                wxPublicAccessToken.getAccessToken(function (token) {
                    request({
                        url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        method: "POST",
                        timeout: 10000,
                        encoding: null,
                        json: {
                            "code": member.code,
                            "card_id": memberCardNumber,
                            "bonus": member.point
                        }
                    }, function (error, response, body) {
                        console.log(error)
                        res.ok('添加消费记录完成')
                    })
                })
            }else{
                res.ok('添加消费记录完成')
            }
            // if(changePoint>0 && req.body.givePoint==1){
            //     let newPointHistory = new PointHistory({
            //         openid: user.openid,
            //         unionID: user.unionID,
            //         member: member._id,
            //         expenseHistory: newExpenseHistory._id,
            //         expenseDate: newExpenseHistory.updatedAt,
            //         manual: 0, // 1位人工，0为自动
            //         amount: changePoint, // 变动的积分数量
            //         type: 0, // 0 为加，1为减
            //         isDelete: 0,
            //     })
            //     await newPointHistory.save()
            //     member.point = member.point + changePoint
            //     member.updatedAt = new Date()
            //     await member.save()
            //     userPoint.total = userPoint.total + changePoint
            //     if(userPoint.total>=10000){
            //         user.vip = 1
            //         member.type = "VIP会员"
            //         await user.save()
            //         await member.save()
            //     }
            //     userPoint.current = userPoint.current + changePoint
            //     userPoint.updatedAt = new Date()
            //     await userPoint.save()
            //     wxPublicAccessToken.getAccessToken(function(token) {
            //         request({
            //                  url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
            //                  method: "POST",
            //                  timeout: 10000,
            //                  encoding: null,
            //                  json:{
            //                     "code": member.code,
            //                     "card_id": memberCardNumber,
            //                     "bonus": member.point
            //                  }
            //              },function(error, response, body){
            //                 console.log(error)
            //                 res.ok('添加消费记录完成')
            //         })
            //     })
            // }else{
            //     res.ok('添加消费记录完成')
            // }
        } catch (e) {
            next(e)
        }
    },
    
    addUserExpenseHistoryNotGivePoint: async (req, res, next) => {
        try {
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let user = await User.findOne({ _id: req.body.user, isDelete: 0 }).exec()
            let store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let payPrice = Number(req.body.amount)
            let point = Number(req.body.point)
            if(!req.body.amount){
                return res.send({code:201,msg:"消费金额未填写"})
            }
            if (req.body.usePoint == 1) {
                // console.log(req.body.point,userPoint.current)
                if (point > userPoint.current) {
                    return res.send({ code: 201, msg: '积分不足' })
                }
                // console.log(payPrice,point,payPrice<point)
                if (payPrice < point) {
                    return res.send({ code: 201, msg: '使用积分大于消费金额' })
                }
                payPrice = payPrice - point
            }
            let changePoint = 0
            let attribute = store.attribute
            if (user.vip == 1) {
                attribute = store.attributeVIP
            }
            let newExpenseHistory = new ExpenseHistory({
                openid: user.openid,
                unionID: user.unionID,
                cellphone: user.cellphone,
                store: req.body.store,
                member: member._id,
                updatedAt: new Date(),
                isDelete: 0,
                usePoint: req.body.usePoint, //0不使用，1使用
                amount: req.body.amount, // 价格（未抵扣积分）
                payPrice: payPrice, //支付价格（抵扣积分后）
                point: point,
                earnPoints: changePoint,
                pendingPoint:changePoint,
                memo: req.body.memo, //人工操作备注
                rate: attribute, //10为10%
                account: req.session.user._id,
                verify: 0,
                review:0,
                billNumber:req.body.billNumber,
                billImage:req.body.billImage
            })
            await newExpenseHistory.save()
            if (changePoint > 0) {
                if(userPoint.pendingPoint==undefined){
                    userPoint.pendingPoint =changePoint
                }else{
                    userPoint.pendingPoint = userPoint.pendingPoint + changePoint
                }
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            if (req.body.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: newExpenseHistory._id,
                    expenseDate: newExpenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: point, // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point - point
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current - point
                userPoint.updatedAt = new Date()
                await userPoint.save()
                wxPublicAccessToken.getAccessToken(function (token) {
                    request({
                        url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        method: "POST",
                        timeout: 10000,
                        encoding: null,
                        json: {
                            "code": member.code,
                            "card_id": memberCardNumber,
                            "bonus": member.point
                        }
                    }, function (error, response, body) {
                        console.log(error)
                        res.ok('添加消费记录完成')
                    })
                })
            }else{
                res.ok('添加消费记录完成')
            }
        } catch (e) {
            next(e)
        }
    },


    recallUserExpenseHistory: async (req, res, next) => {
        try {
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            expenseHistory.isDelete = 1
            await expenseHistory.save()
            let user = await User.findOne({ unionID: expenseHistory.unionID, isDelete: 0 }).exec()
            let member = await Member.findOne({ unionID: expenseHistory.unionID, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ unionID: expenseHistory.unionID, isDelete: 0 }).exec()
            if (expenseHistory.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: expenseHistory._id,
                    expenseDate: expenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: expenseHistory.point, // 变动的积分数量
                    type: 0, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point + expenseHistory.point
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current + expenseHistory.point
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            if(expenseHistory.verify == 1){
                if (expenseHistory.earnPoints > 0) {
                    let newPointHistory = new PointHistory({
                        openid: user.openid,
                        unionID: user.unionID,
                        member: member._id,
                        expenseHistory: expenseHistory._id,
                        expenseDate: expenseHistory.updatedAt,
                        manual: 0, // 1位人工，0为自动
                        amount: expenseHistory.earnPoints, // 变动的积分数量
                        type: 1, // 0 为加，1为减
                        isDelete: 0,
                    })
                    await newPointHistory.save()
                    member.point = member.point - expenseHistory.earnPoints
                    member.updatedAt = new Date()
                    await member.save()
                    userPoint.total = userPoint.total - expenseHistory.earnPoints
                    userPoint.current = userPoint.current - expenseHistory.earnPoints
                    userPoint.updatedAt = new Date()
                    await userPoint.save()
                }
            }else{
                if (expenseHistory.pendingPoint > 0) {
                    userPoint.pendingPoint = userPoint.pendingPoint - expenseHistory.pendingPoint
                    userPoint.updatedAt = new Date()
                    await userPoint.save()
                }
            }

            // if (expenseHistory.earnPoints > 0) {
            //     let newPointHistory = new PointHistory({
            //         openid: user.openid,
            //         unionID: user.unionID,
            //         member: member._id,
            //         expenseHistory: expenseHistory._id,
            //         expenseDate: expenseHistory.updatedAt,
            //         manual: 0, // 1位人工，0为自动
            //         amount: expenseHistory.earnPoints, // 变动的积分数量
            //         type: 1, // 0 为加，1为减
            //         isDelete: 0,
            //     })
            //     await newPointHistory.save()
            //     member.point = member.point - expenseHistory.earnPoints
            //     member.updatedAt = new Date()
            //     await member.save()
            //     userPoint.total = userPoint.total - expenseHistory.earnPoints
            //     userPoint.current = userPoint.current - expenseHistory.earnPoints
            //     userPoint.updatedAt = new Date()
            //     await userPoint.save()
            // }
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.ok('撤销消费记录完成')
                })
            })
            // res.ok('微信会员卡积分未完成')
        } catch (e) {
            next(e)
        }
    },

    verifyPassed: async (req, res, next) => {
        try {
            let roles = ["root"]
            let role = await Role.find({_id:req.session.user.role,name:roles}).exec()
            if(role.length === 0){
                res.send({code:201,msg:"无审核权限"})
                return false
            }
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            if(expenseHistory.review == 0){
                return res.send({code:201,msg:"未复核，请先复核"})
            }
            if(expenseHistory.verify == 1 || expenseHistory.verify == 2){
                return res.send({code:201,msg:"已审核过"})
            }
            // if(expenseHistory.verify == 2){
            //     expenseHistory.earnPoints = Math.round(expenseHistory.payPrice * expenseHistory.rate / 100)
            // }
            expenseHistory.verify = 1
            expenseHistory.pendingPoint = 0
            expenseHistory.verifyAt = new Date()
            expenseHistory.verifyAccount = req.session.user._id
            await expenseHistory.save()
            let member = await Member.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            let user = await User.findOne({openid:expenseHistory.openid,isDelete:0})
            let newPointHistory = new PointHistory({
                openid: expenseHistory.openid,
                unionID: expenseHistory.unionID,
                member: member._id,
                expenseHistory: expenseHistory._id,
                expenseDate: expenseHistory.updatedAt,
                manual: 0, // 1位人工，0为自动
                amount: expenseHistory.earnPoints, // 变动的积分数量
                type: 0, // 0 为加，1为减
                isDelete: 0,
            })
            await newPointHistory.save()
            member.point = member.point + expenseHistory.earnPoints
            member.updatedAt = new Date()
            await member.save()
            userPoint.total = userPoint.total + expenseHistory.earnPoints
            if (userPoint.total >= 10000) {
                user.vip = 1
                member.type = "VIP会员"
                await user.save()
                await member.save()
            }
            userPoint.current = userPoint.current + expenseHistory.earnPoints
            userPoint.pendingPoint = userPoint.pendingPoint - expenseHistory.earnPoints
            userPoint.updatedAt = new Date()
            await userPoint.save()
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.ok('审核通过', expenseHistory)
                })
            })
        } catch (e) {
            next(e)
        }
    },

    verifyFailed: async (req, res, next) => {
        try {
            let roles = ["root"]
            let role = await Role.find({_id:req.session.user.role,name:roles}).exec()
            if(role.length === 0){
                res.send({code:201,msg:"无审核权限"})
                return false
            }
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            if(expenseHistory.review == 0){
                return res.send({code:201,msg:"未复核，请先复核"})
            }
            if(expenseHistory.verify == 1 || expenseHistory.verify == 2){
                return res.send({code:201,msg:"已审核过"})
            }
            let userPoint = await UserPoint.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            userPoint.pendingPoint = userPoint.pendingPoint - expenseHistory.earnPoints
            await userPoint.save()
            expenseHistory.verify = 2
            expenseHistory.pendingPoint = 0
            expenseHistory.verifyAt = new Date()
            expenseHistory.earnPoints = 0
            expenseHistory.verifyAccount = req.session.user._id
            await expenseHistory.save()
            res.ok('审核未通过', expenseHistory)
        } catch (e) {
            next(e)
        }
    },


    reviewPassed: async (req, res, next) => {
        try {
            let roles = ["root","店长"]
            let role = await Role.find({_id:req.session.user.role,name:roles}).exec()
            if(role.length === 0){
                res.send({code:201,msg:"无复核权限"})
                return false
            }
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            expenseHistory.review = 1
            expenseHistory.reviewAt = new Date()
            expenseHistory.reviewAccount=req.session.user._id
            await expenseHistory.save()
            res.ok('复核通过', expenseHistory)
        } catch (e) {
            next(e)
        }
    },

    reviewFailed: async (req, res, next) => {
        try {
            let roles = ["root","店长"]
            let role = await Role.find({_id:req.session.user.role,name:roles}).exec()
            if(role.length === 0){
                res.send({code:201,msg:"无复核权限"})
                return false
            }
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            userPoint.pendingPoint = userPoint.pendingPoint - expenseHistory.earnPoints
            await userPoint.save()
            expenseHistory.review = 2
            expenseHistory.reviewAt = new Date()
            expenseHistory.verify = 2
            expenseHistory.pendingPoint = 0
            expenseHistory.verifyAt = new Date()
            expenseHistory.earnPoints = 0
            expenseHistory.reviewAccount=req.session.user._id
            await expenseHistory.save()
            res.ok('复核未通过', expenseHistory)
        } catch (e) {
            next(e)
        }
    },

    uploadBillImage: async (req, res, next) => {
        try {
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            expenseHistory.billImage = req.body.billImage
            expenseHistory.updatedAt = new Date()
            await expenseHistory.save()
            res.ok('添加账单图片成功', expenseHistory)
        } catch (e) {
            next(e)
        }
    },

    changeEarnPoints: async (req, res, next) => {
        try {
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            expenseHistory.originalEarnPoints = expenseHistory.earnPoints
            expenseHistory.earnPoints = req.body.point
            expenseHistory.changePointAccount= req.session.user._id
            expenseHistory.changePointDate = new Date()
            await expenseHistory.save()
            res.ok('修改积分成功', expenseHistory)
        } catch (e) {
            next(e)
        }
    },

    changeExpenseHistoryPrice: async (req, res, next) => {
        try {
            let roles = ["root","店长"]
            let role = await Role.find({_id:req.session.user.role,name:roles}).exec()
            if(role.length === 0){
                res.send({code:201,msg:"无复核权限"})
                return false
            }
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            if(expenseHistory.verify !=0){
                return res.send({code:201,msg:"消费记录已审核无法修改"})
            }
            // let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let user = await User.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            let store = await Store.findOne({ _id: expenseHistory.store, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: expenseHistory.openid, isDelete: 0 }).exec()
            let amount = Number(expenseHistory.amount)
            let oldPayPrice = Number(expenseHistory.payPrice)
            let oldPoint = Number(expenseHistory.point)
            let newPrice = Number(req.body.newPrice)
            let oldEarnPoints = Number(expenseHistory.earnPoints)
            if(!req.body.newPrice){
                return res.send({code:201,msg:"消费金额未填写"})
            }
            if (expenseHistory.usePoint == 1) {
                if (newPrice < oldPoint) {
                    return res.send({ code: 201, msg: '使用积分大于消费金额' })
                }
                newPrice = newPrice - oldPoint
            }
            let changePoint = Math.round(newPrice * store.attribute / 100)
            let attribute = store.attribute
            if (user.vip == 1) {
                changePoint = Math.round(newPrice * store.attributeVIP / 100)
                attribute = store.attributeVIP
            }
            if(expenseHistory.notGivePoint == 1){
                changePoint = 0
            }
            expenseHistory.updatedAt = new Date()
            expenseHistory.amount = newPrice
            expenseHistory.payPrice = newPrice
            expenseHistory.earnPoints = changePoint
            expenseHistory.pendingPoint = changePoint
            expenseHistory.account = req.session.user._id
            await expenseHistory.save()
            if (changePoint > 0) {
                if(userPoint.pendingPoint==undefined){
                    userPoint.pendingPoint =changePoint
                }else{
                    userPoint.pendingPoint = userPoint.pendingPoint - oldEarnPoints + changePoint
                }
                userPoint.changePriceAccount = req.session.user._id
                userPoint.changePriceDate = new Date()
                await userPoint.save()
            }
            res.ok('修改金额成功', expenseHistory)
        } catch (e) {
            next(e)
        }
    },

};